import Vue from 'vue'
import VueRouter from 'vue-router'
import store from './../store/store'
import * as types from './../store/types'
 
//组件模块
import HelloWorld from './../components/HelloWorld';
import Test from './../components/Test';
import Login from './../page/Login';
 
Vue.use(VueRouter)
 
const routes = [
  { path: '/login', name: 'login', component: Login },
  { path: '/hello', name: 'hello', component: HelloWorld },
  { 
    path: '/test', 
    name: 'test', 
    component: Test ,
    meta: {
      requireAuth: true,
    }
},
{ path: '*', redirect: '/login'}
];

// 页面刷新时，重新赋值token
if (window.localStorage.getItem('token')) {
  store.commit(types.LOGIN, window.localStorage.getItem('token'))
}

const router = new VueRouter({
  routes
});

router.beforeEach((to, from, next) => {
  if (to.matched.some(r => r.meta.requireAuth)) {
      if (store.state.token) {
          next();
      }
      else {
          next({
            path: '/login',
            query: {redirect: to.fullPath}
        })
      }
  }
  else {
      next();
  }
})

export default router;
